package util;

import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.apache.commons.configuration.reloading.FileChangedReloadingStrategy;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/***
 * conf/config.properties 的配置信息，仅存放系统通用的必须信息：数据库配置，serverIdentify等。
 * @author Administrator
 *
 */
public class AppConfig {

	private static final Logger logger = Logger.getLogger(AppConfig.class);
	
	protected static PropertiesConfiguration noticeProperties = new PropertiesConfiguration();
	static{
		try{
			//装载配置文件中配置项
			init("config.properties","NOTICE_HOME");	
		}catch(Exception e){
			logger.error("Configure init,error:",e);
		}
//		init("/htmlmicrocard.properties");
	}
	
	
	
    protected static String getProperty(String key, String defaultValue) {
		return noticeProperties.getString(key, defaultValue);
	}
	protected static boolean getProperty(String key, boolean defaultValue) {
		return noticeProperties.getBoolean(key, defaultValue);
	}

	protected static int getProperty(String key, int defaultValue) {
		return noticeProperties.getInt(key, defaultValue);
	}

	protected static long getProperty(String key, long defaultValue) {
		return noticeProperties.getLong(key, defaultValue);
	}
	

	
	
	protected static void init(final String propertyFileName,final String homedir) throws ConfigurationException {
		Map<String,String> systemVariableMap = System.getenv();
		String path=systemVariableMap.get(StringUtils.upperCase(homedir));
		if(StringUtils.isEmpty(path)){
			path=systemVariableMap.get(StringUtils.lowerCase(homedir));
		}
		//分隔符失效,用","隔开的分隔符仍然解析成字符串，不解析成list
		noticeProperties.setDelimiterParsingDisabled(true);
		if(StringUtils.isNotEmpty(path)){
			path=new StringBuilder(path).append(File.separator).append("conf").append(File.separator).append(propertyFileName).toString();
			File file=new File(path);
			if(file.exists()){
				noticeProperties.load(path);
			}else{
				logger.warn("没有找到文件"+path+",从classpath中加载"+propertyFileName);
				
				loadConfigFromClassPath(propertyFileName);
			}
		}else{
			loadConfigFromClassPath(propertyFileName);
		}
		//配置文件文件自动重载策略
		FileChangedReloadingStrategy reloadStrategy=new FileChangedReloadingStrategy();
		reloadStrategy.setRefreshDelay(getReloadPropertiesInterval());
		noticeProperties.setReloadingStrategy(reloadStrategy);
	}


	private static void loadConfigFromClassPath(final String propertyFileName)
			throws ConfigurationException {
		URL fileUrl=AppConfig.class.getResource(propertyFileName);
		if (fileUrl != null) {
			noticeProperties.load(fileUrl);
		} 
	}
	
	/**
	 * 重载配置文件的时间间隔，默认60s
	 * @return
	 */
	public static long getReloadPropertiesInterval(){ return getProperty("reload.properties.interval",60000); }
	
	public static String SERVER_IDENTITY = getProperty("server.identity","");
	/**
	 * 数据分批处理的批次大小，经过测试，1000是个比较合理的值
	 */
	public static final int DATA_BATCH_SIZE=getProperty("data.batch.size",5000);
	
	public static final int MemberMaxLimit=2000;
	/***
	 * 阅后即焚 的时间值
	 */
	public static final long READ_TO_DELETE_TIME=getProperty("read.to.delete.time",30L);
	
	/**
	 * 是否需要执行调度,每个集群中只需要一个节点执行即可.
	 */
	public static boolean NEED_SCHEDULE=getProperty("notice.isNeedSchedule",true);

	public static final boolean UNCONFIRM_REMIND_SWITCH = getProperty("unconfirm.remind.switch",false);

	public static List<Integer> getRemindTimePercent(){
		//配置中获取的是百分比的分子
		String timePoint = getProperty("unconfirm.remind.time.percent", "20,50,80");
		if(StringUtils.isBlank(timePoint)){
			return Arrays.asList(20,50,80);
		}else{
			String[] timePointStr = timePoint.split(",");
			List<Integer> list = new ArrayList();
			for (String str : timePointStr){
				list.add(Integer.valueOf(str));
			}
			if(CollectionUtils.isEmpty(list)){
				list = Arrays.asList(20,50,80);
			}
			return list;
		}
	}
	
}
